import os
from flask import send_file, make_response
from src.schema.hosting import file_download_schema
from src.core.variables.cls import HOSTING_JAVA_RUNNER_DICT, HOSTING_STATIC_RUNNER_DICT
from src.core.variables.status import SUCCESS_CODE, ERROR_CODE_CUSTOMIZE
import urllib.parse


def java(schema: file_download_schema):
    runner = HOSTING_JAVA_RUNNER_DICT.get(schema.app_id)
    if not runner or not os.path.isfile(runner.file_path):
        return ERROR_CODE_CUSTOMIZE("文件不存在", 404)

    # 记录下载日志（可选）
    # app.logger.info(f"用户 {user.id} 下载文件: {runner.file_path}")

    # 获取文件名并进行URL编码
    filename = os.path.basename(runner.file_path)
    encoded_filename = urllib.parse.quote(filename.encode('utf-8'))
    
    # 直接返回文件流
    response = make_response(
        send_file(
            runner.file_path,
            as_attachment=True,
            download_name=filename,
            conditional=True,
        )
    )

    # 设置Content-Disposition头，确保浏览器能正确识别文件名
    response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"
    
    # 禁用缓存确保每次都是最新文件
    response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"

    return response


def static(schema: file_download_schema):
    ...